package com.weige.elefence.service;

import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.weige.elefence.annotation.Service;
import com.weige.elefence.mq.Product;
import com.weige.elefence.utils.ReadJsonFileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ltj
 * @Description MQ业务层耦合
 * @date 2022/5/25
 */
@Service
public class MqService {
    private static final Logger log = LoggerFactory.getLogger(MqService.class);

    private final Channel channel;
    private final String exchange;
    private final String routeKey;
    private String devId;
    private String devName;

    {
        channel = Product.channel;
        Map<String, String> map = ReadJsonFileUtil.map;
        exchange = map.get("exchange");
        routeKey = map.get("route-key");
    }

    public boolean send(Object message) {
        try {
            byte[] bytes = null;
            if (message instanceof String) {
                bytes = ((String) message).getBytes();
            }
            // 在该信道上开启发送者确认
            channel.confirmSelect();
            // 第一个是交换机名称，第二个是队列的路由键
            channel.basicPublish(exchange, routeKey, this.getBasicProperties(), bytes);
            boolean b = channel.waitForConfirms();
            if (b) {
                log.info("发送成功");
                return true;
            }
            log.info("发送失败");
            return false;
        } catch (IOException | InterruptedException ex) {
            ex.printStackTrace();
            return false;
        }
    }

    private BasicProperties getBasicProperties() {
        Map<String, Object> headers = new HashMap<String, Object>(16);
        // 设备id
        headers.put("devId", devId);
        // 设备名称
        headers.put("devName", devName);
        // 厂商ID
        headers.put("manufactureId","ShuyanyuanAIGateway");
        // 产品型号
        headers.put("model", "acs_master");
        // 服务标识serviceId
        headers.put("serviceName", "userAccessRecordService");
        return new BasicProperties.Builder()
                // 头部
                .headers(headers)
                //有效期
                .expiration("60000")
                .build();
    }
}
